package com.framework.main.sys.role.service;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import com.framework.base.constant.ActionConstants;
import com.framework.base.constant.WebConstants;
import com.framework.base.dao.IDManager;
import com.framework.base.service.BaseServiceImp;
import com.framework.base.service.ServiceException;
import com.framework.base.struts.BaseVo;
import com.framework.base.struts.Result;
import com.framework.main.sys.role.dao.RoleDao;
import com.framework.main.sys.role.domain.RoleVO;
import com.framework.main.sys.user.dao.RecurResource;
import com.framework.main.sys.user.dao.UserDao;
import com.framework.main.sys.user.domain.SysDataAuthority;
import com.framework.main.sys.user.domain.SysRoleModuleVO;
import com.framework.main.sys.user.domain.SysUserRoleVO;
import com.framework.main.sys.user.domain.UserVo;


/**
 * Title:角色（ServiceImp） 
 * Description:处理与角色相关的业务
 * tabaleName(对应的表名): SYS_ROLE
 * Copyright: 2011
 * Company: framework
 * @author：邹乐乐
 * @version 1.0
 * @Date May 30, 2011 4:48:47 PM
 */
public class RoleServiceImp extends BaseServiceImp implements RoleService{
	private RoleDao roleDao;
	private UserDao userDao;
	
	public RoleDao getRoleDao() {
		return roleDao;
	}
	
	public void setRoleDao(RoleDao roleDao) {
		this.roleDao = roleDao;
	}

	public UserDao getUserDao() {
		return userDao;
	}

	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}

	/**
	 * 拼接SQL查询条件
	 */
	@Override
	public String populatePageHQL(Map<String,Object> paramsMap, String orderByFields,
			String orderType) throws Exception {
		return super.populatePageHQL(paramsMap, orderByFields, orderType);
	}
	
	
	@SuppressWarnings("unchecked")
	public List<UserVo> toselectUser(String url, String pk) throws Exception {
		return getRoleDao().query(url, pk);
	}
	/**
	 * 重写删除方法 只能是数据进行修改状态，并不对数据进行物理删除
	 */
	public String doDelete(String[] pks) throws Exception {
		if (pks != null && pks.length > 0) {
			this.getBaseDao().doDelete("doDeleteRole", pks);
		}
		return ActionConstants.RELOAD;
	}
	public void doInsertUR(String pk,String userid)throws Exception{		
		//删除人员-角色中间表
		this.getBaseDao().doUpdate("doDeleteUR", pk);
		String[] ss=userid.split(",");
		for (String uidf : ss) {
			SysUserRoleVO vo=new SysUserRoleVO();
			vo.setIdf(IDManager.generateID());
			vo.setRoleIdf(pk);
			vo.setUseridf(uidf);
			this.getBaseDao().doInsert("doInsertUR", vo);
		}
	}
	/**
	 * 修改分配角色的权限
	 * 
	 * @param cfg
	 *            ActionParameter
	 * @throws Exception
	 * @return ActionForward
	 */
	@SuppressWarnings("unchecked")
	public Result toDistribute(String pk) throws Exception {
		Map<String,Object> cfg=new HashMap<String,Object>();

		List selectedModules = new ArrayList(); // 定义容器->用于保存角色已有的操作模块;
		List selectedOperations = new ArrayList(); // 定义容器->用于保存角色已有的权限代码;
		List selectedDataAuthority = getUserDao().queryForList("toListdataAuthority", pk);

		List temp = 
			getUserDao().queryForList(
				"toListRoleModuOper", pk); // 查询得到角色已有的操作模块和权限代码;
		for (int i = 0; i < temp.size(); i++) {
			SysRoleModuleVO us = (SysRoleModuleVO) temp.get(i);
			selectedModules.add(us.getModule_ID()); // 存入模块容器
			selectedOperations.add(us.getPermission_Code()); // 存入权限代码容器;
		}

		// 构建操作模块树
		RecurResource r = new RecurResource();
		r.selectedModules = selectedModules; // 角色已有模块
		r.selectedOperations = selectedOperations; // 角色已有的操作权限;
		r.selectedDataAuthority = selectedDataAuthority;
		r.recurResource("-2");
		cfg.put("recurResource", r);
		cfg.put("fid", pk);
		return new Result(ActionConstants.SUCCESS,cfg);
	}
	
	
	
	/**
	 * 保存角色分配权限的操作
	 * 
	 * @param cfg
	 *            ActionParameter
	 * @throws Exception
	 * @return ActionForward
	 */
	@SuppressWarnings("unchecked")
	public Result doDistribute(String pk ,String[] value,String[] value2,String scope) throws Exception {
		Map<String,Object> cfg=new HashMap<String,Object>();
		
		
		String[] moduAndOper =new String[value.length+value2.length];
		System.arraycopy(value,0,moduAndOper,0,value.length); 
		System.arraycopy(value2,0,moduAndOper,value.length,value2.length); //合并数组

		// 先删除该角色的所有权限
		
		List opList = getUserDao().queryForList(
				"toListRoleModuOper", pk);
		
		try{
		for (int i = 0; i < opList.size(); i++) {
			SysRoleModuleVO opRole = (SysRoleModuleVO) opList.get(i);
			 getUserDao().doDelete("doDeleteRoleModuOper",new String[]{opRole.getID()}); 
		}

		if (moduAndOper != null) {
			// 插入所选的新权限
			for (int i = 0; i < moduAndOper.length; i++) {
				String[] op = moduAndOper[i].split(",");

				String module = op[0];
				String permission_Code = "";
				String remark = "";
				if (op.length > 1) {
					permission_Code = op[1];
				}
				if (op.length > 2) {
					remark = op[2];
				}

				SysRoleModuleVO vo = new SysRoleModuleVO();
				vo.setID(IDManager.generateID());
				vo.setRole_ID(pk);
				vo.setModule_ID(module);
				vo.setPermission_Code(permission_Code); // (1)
				vo.setRemark(remark);

				getUserDao().doInsert("doInsertRoleModuOper", vo);
			}
		}
		if(!(scope.equals("")||scope==null)){
			String[] data = scope.split(";");
			for(int i=0;i<data.length;i++){
				String[] sc = data[i].split(",");
				SysDataAuthority sda = new SysDataAuthority();
				sda.setMenuIdf(sc[0].substring(1));
				int dataScopef = Integer.valueOf(sc[1]);
				sda.setDataScopef(dataScopef);
				sda.setRoleIdf(pk);
				getUserDao().doUpdate("doUpdatedataAuthority", sda);
			}
		}
	}catch (ServiceException e) {//事务回滚
		e.printStackTrace();
		throw new Exception("保存角色分配权限的操作失败");
	}

		cfg.put("actionMsg", "操作信息：保存角色权限成功！");
		return new Result(ActionConstants.RELOAD,cfg);
	}
	
	/**
	 * dwr调用，取出所有角色
	 * @return
	 * @throws Exception
	 * @author：gyd
	 */
	public List<?> toListRole() throws Exception{
		List<BaseVo> roleList=this.getBaseDao().queryForList("toList", " sys_role order by " + WebConstants.DEFAULTORDERFIDS+" asc");
		Map middleMap=new HashMap();
		Iterator iter=roleList.iterator();
		while(iter.hasNext()){
			RoleVO role=(RoleVO)iter.next();
			middleMap.put(role.getIdf(), role);
		}
		List<?> userList=this.getUserDao().queryForList("toSelectUsersByRole", "");
		Iterator userIt=userList.iterator();
		while(userIt.hasNext()){
			UserVo user=(UserVo)userIt.next();
			if(user!=null){
				RoleVO roleVo=(RoleVO)middleMap.get(user.getRoleIdf());
				if(roleVo!=null){
					if(roleVo.getUserList()==null){
						roleVo.setUserList(new ArrayList());
					}
					roleVo.getUserList().add(user);
					middleMap.put(roleVo.getIdf(),roleVo);
				}
			}
		}
		roleList=new ArrayList();
		for (Object object : middleMap.values()){
			roleList.add((BaseVo)object);
		}
		return roleList;
	}
}
